<?php

/**
 * @author Nguyen Thai Binh
 */
if (!defined('BASEPATH'))
  exit('No direct script access allowed');

class Api extends CI_Controller {

  public $base_lib;

  public function __construct() {
    parent::__construct();
    $this->base_lib = new Base_lib(DB_TABLE_USER);
  }

  private function sec($sec) {
    $sec = base64_decode($sec);
    $sec = explode(';', $sec);
    if (count($sec) == 5) {
      $user = $this->user_model->get(array('id' => $sec[0], 'username' => $sec[1], 'password' => $sec[3]));
      if ($user) {
        $end_user = $this->end_user_model->get(array('user_id' => $sec[0], 'id' => $sec[2]));
        if ($end_user)
          return $end_user;
      }
    }
    return null;
  }

  public function test_sec($sec = '') {
    echo $this->sec($sec);
  }

  public function login() {
    $username = empty($_REQUEST['username']) ? '' : base64_decode($_REQUEST['username']);
    $password = empty($_REQUEST['password']) ? '' : $_REQUEST['password'];
    $end_user = $this->end_user_model->get(array('email' => $username, 'status' => PROFILE_STATUS_ACTIVE));
    if (!empty($end_user)) {
      $user = $this->user_model->get(array('id' => $end_user['user_id'], 'is_active' => true));
      if ($user) {
        $password = md5($user['salt'] . $password);
        if ($user["password"] == $password) {
          $user['last_login'] = time();
          $this->user_model->save($user);
          $end_user['last_login'] = time();
          $this->end_user_model->save($end_user);
          set_userdata('end_user_user_id', $user['id']);
          set_userdata('end_user_role', 'END-USER');
          set_userdata('end_user_display_name', $user['display_name']);
          set_userdata('end_user_id', $end_user['id']);
          set_userdata('end_user_avatar', $end_user['avatar']);
          $end_user['avatar'] = site_url('service/api/get_img_from_path?path=end_user/' . $end_user['avatar']);

          $end_user['country'] = $this->country_model->get($end_user['country_id']);
          $end_user['state'] = $this->state_model->get($end_user['state_id']);
          $end_user['city'] = $this->city_model->get($end_user['city_id']);
          $sec = base64_encode($user['id'] . ';' . $user['username'] . ';' .
                  $end_user['id'] . ';' . $user['password'] . ';' . time());
          unset($user['password']);
          unset($user['salt']);
          unset($user['id']);
          unset($user['created_on']);
          unset($user['last_login']);
          unset($end_user['date_create']);
          unset($end_user['date_update']);
          unset($end_user['id']);
          unset($end_user['user_id']);
          unset($end_user['country_id']);
          unset($end_user['city_id']);
          $temp = json_encode(array(
              'msg' => $this->lang->line('message.data'), 'status' => 1,
              'sec' => $sec, 'profile' => array_merge($user, $end_user)));
          echo str_replace('\\/', '/', $temp);
          return;
        }
      }
    }
    echo json_encode(array(
        'msg' => $this->lang->line('error.authentication.fail'), 'status' => 0,
        'reason' => $this->lang->line('error.login.wrong')));
  }

  public function logout() {
    unset_userdata('end_user_user_id');
    unset_userdata('end_user_role');
    unset_userdata('end_user_display_name');
    unset_userdata('end_user_id');
    unset_userdata('end_user_avatar');
    echo json_encode(array('msg' => $this->lang->line('msg.logout.success'), 'status' => 1));
  }

  public function forgot_password() {
    $email = empty($_REQUEST['email']) ? '' : $_REQUEST['email'];
    if (!validate_email($email)) {
      $email = base64_decode($email);
    }
    $end_user = $this->end_user_model->get(array('email' => $email));
    if ($end_user) {
      $user = $this->user_model->get($end_user['user_id']);
      if ($user) {
        $user['active_code'] = $this->auth->generateActiveCode(50) . uniqid();
        $this->load->library('sendEmail');
        $send = $this->sendemail->sendEmailByTemplate(array_merge($end_user, $user, array(
                    'from' => $this->setting_model->item("sender_name"),
                    'link' => site_url('forgot_password/request_password/' . $user['active_code']),
                    'to' => $end_user['email'])), 'end_user_forgot_password');
        if ($send) {
          $this->user_model->save($user);
          echo json_encode(array('msg' => $this->lang->line('message.request.change_password.success'), 'status' => 1, 'reason' => ''));
        } else {
          echo json_encode(array(
              'msg' => $this->lang->line('error.request.change_password.fail'), 'status' => 0,
              'reason' => $this->lang->line('error.request.change_password.fatal.error')));
        }
      } else {
        echo json_encode(array(
            'msg' => $this->lang->line('error.request.change_password.fail'), 'status' => 0,
            'reason' => $this->lang->line('error.require.change_password.email.not.exist')));
      }
    } else {
      echo json_encode(array(
          'msg' => $this->lang->line('error.request.change_password.fail'), 'status' => 0,
          'reason' => $this->lang->line('error.require.change_password.email.not.exist')));
    }
  }

  public function registry() {
    $params = $_REQUEST;
    $params['username'] = empty($params['username']) ? (empty($params['email']) ? '' :
                    base64_decode($params['email'])) : base64_decode($params['username']);
    $params['email'] = $params['username'];
    $user = $this->user_model->create_obj($params);
    $end_user = $this->end_user_model->create_obj($params);
    $errors = array();
    if (empty($user['username']))
      $errors['username'] = $this->lang->line('error.field.require', 'email');
    else if (strlen($user['username']) < 3)
      $errors['username'] = $this->lang->line('error.field.min', array('email', 3));
    else if (!validate_email($user['username']))
      $errors['username'] = $this->lang->line('error.field.allow.character', $user['username']);
    else if (!$this->base_lib->check_exist($user['username'], 'username', $user['id']))
      $errors['username'] = $this->lang->line('error.field.exist', array('E-mail', $user['username']));
    if (empty($user['password']))
      $errors['password'] = $this->lang->line('error.field.require', 'password');
    else if (strlen($user['password']) < 6)
      $errors['password'] = $this->lang->line('error.field.min', array('password', 6));
    else if (strlen($user['password']) < 6 && strlen($user['password']) > 0)
      $errors['password'] = $this->lang->line('error.field.min', array('password', 6));

    $errors = array_merge($errors, $this->end_user_model->validate($end_user));
    if (empty($errors)) {
      $user['salt'] = $this->auth->generateActiveCode(10);
      $user['password'] = $user['confirm_pass'] = md5($user['salt'] . $user['password']);
      if ($this->setting_model->item('enviroment') == EVR_TEST) {
        $user['is_active'] = true;
      } else
        $user['is_active'] = false;
      $group = $this->group_model->get(array('name' => 'End User'));
      if (!empty($group)) {
        $user['group_id'] = $group['id'];
      } else
        $user['group_id'] = 0;
      $user = $this->user_model->save($user);
      if (is_integer($user)) {
        $end_user['user_id'] = $user;
        if ($this->setting_model->item('enviroment') == 1 || !$this->setting_model->item('require_active_via_email')) {
          $end_user['status'] = PROFILE_STATUS_ACTIVE;
        } else {
          $end_user['status'] = PROFILE_STATUS_UNACTICE;
        }
        $end_user_id = $this->end_user_model->save($end_user);
        if (is_integer($end_user_id)) {
          if ($this->setting_model->item('require_active_via_email')) {
            $this->load->library('end_user_lib');
            $this->end_user_lib->email_active_account(array_merge($user, $end_user));
          }
          echo json_encode(array('msg' => $this->lang->line('message.end_user.registry.success', $params['username']), 'status' => 1));
          return;
        } else
          $this->user_model->delete($user);
      }
      echo json_encode(array(
          'msg' => $this->lang->line('error.faltal.error'), 'status' => 0,
          'reason' => $this->lang->line('error.faltal.error'),
          'errors' => $this->lang->line('error.faltal.error')));
      return;
    }
    echo json_encode(array(
        'msg' => $this->lang->line('message.end_user.registry.fail'), 'status' => 0, 'errors' => $errors));
  }

  public function list_country() {
    $this->db->order_by('name', 'asc');
    echo json_encode(array('msg' => $this->lang->line('message.list.country'), 'status' => 1,
        'countries' => $this->country_model->get_all()
    ));
  }

  public function list_state() {
    $this->db->order_by('name', 'asc');
    echo json_encode(array(
        'msg' => $this->lang->line('message.list.state'), 'status' => 1,
        'states' => $this->state_model->get_all()));
  }

  public function list_city() {
    $this->db->order_by('name', 'asc');
    echo json_encode(array(
        'msg' => $this->lang->line('message.list.city'), 'status' => 1,
        'cities' => $this->city_model->get_all()));
  }

  public function list_state_by_country($country_id = '') {
    if (empty($country_id))
      $country_id = isset($_REQUEST['country_id']) ? $_REQUEST['country_id'] : 0;
    $this->db->where(array('country_id' => $country_id));
    $this->db->order_by('name', 'asc');
    echo json_encode(array(
        'msg' => $this->lang->line('message.list.state'), 'status' => 1,
        'states' => $this->state_model->get_all(array('country_id' => $country_id))));
  }

  public function list_city_by_state($state_id = '') {
    if (empty($state_id))
      $state_id = isset($_REQUEST['state_id']) ? $_REQUEST['state_id'] : 0;
    $this->db->where(array('state_id' => $state_id));
    $this->db->order_by('name', 'asc');
    echo json_encode(array(
        'msg' => $this->lang->line('message.list.city'), 'status' => 1,
        'cities' => $this->city_model->get_all(array('state_id' => $state_id))));
  }

  public function list_category() {
    $this->db->order_by('name', 'asc');
    $categories = $this->category_model->get_all();
    $temp = array();
    foreach ($categories as $i => $cat) {
      $categories[$i]['avatar'] = site_url('service/api/get_img_from_path?path=category/' . $cat['avatar']);
      $cat_promotions = $this->category_promotion_model->get_all(array('cat_id' => $cat['id']));
      $promotion_id = array('id' => array(0));
      foreach ($cat_promotions as $cat_promotion)
        $promotion_id['id'][] = $cat_promotion['promotion_id'];
      $conditions = array('status' => PROMOTION_PUBLISH, 'start_date <= ' => time(),
          'end_date >= ' => time(), 'remain > ' => 0);
      if (userdata('country_id'))
        $conditions['country_id'] = userdata('country_id');
      if (userdata('state_id'))
        $conditions['state_id'] = userdata('state_id');
      if (userdata('city_id'))
        $conditions['city_id'] = userdata('city_id');
      $categories[$i]['num_promotions'] = $this->promotion_model->count($conditions, null, $promotion_id);
      $temp[] = $categories[$i];
    }
    $t = json_encode(array(
        'msg' => $this->lang->line('message.list.category'),
        'status' => 1, 'categories' => $temp));
    echo str_replace('\\/', '/', $t);
  }

  public function profile() {
    if (!userdata('end_user_id')) {
      $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
      $end_user_id = $end_user['id'];
    } else {
      $end_user = $this->end_user_model->get(userdata('end_user_id'));
      $end_user_id = userdata('end_user_id');
    }
    if (!empty($end_user)) {
      $user = $this->user_model->get($end_user['user_id']);
      if (!empty($user)) {
        if (!empty($end_user)) {
          unset($user['password']);
          unset($user['salt']);
          unset($user['id']);
          unset($user['created_on']);
          unset($user['last_login']);
          unset($end_user['date_create']);
          unset($end_user['date_update']);
          unset($end_user['id']);
          unset($end_user['user_id']);
          $end_user['country'] = $this->country_model->get($end_user['country_id']);
          $end_user['city'] = $this->city_model->get($end_user['city_id']);
          $end_user['state'] = $this->state_model->get($end_user['state_id']);
          unset($end_user['country_id']);
          unset($end_user['city_id']);
          $end_user['avatar'] = site_url('service/api/get_img_from_path?path=end_user/' . $end_user['avatar']);
          $temp = json_encode(array(
              'msg' => $this->lang->line('message.data'), 'status' => 1,
              'profile' => array_merge($user, $end_user)));
          echo str_replace('\\/', '/', $temp);
        }
        return;
      }
      echo json_encode(array('msg' => $this->lang->line('error.user.not.found'), 'status' => 0,
          'reson' => $this->lang->line('error.user.not.found')));
    } else {
      echo json_encode(array('msg' => $this->lang->line('error.authentication.require'), 'status' => 0,
          'reason' => $this->lang->line('message.require.login.as.end_user')
      ));
    }
  }

  public function update_profile() {
    if (userdata('end_user_id') || $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '')) {
      if (!userdata('end_user_id')) {
        $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
        $end_user_id = $end_user['id'];
      } else {
        $end_user_id = userdata('end_user_id');
        $end_user = $this->end_user_model->get(userdata('end_user_id'));
      }
      if (!empty($end_user)) {
        $user = $this->user_model->get($end_user['user_id']);
        if ($user) {
          if (isset($_REQUEST['email'])) {
            $end_user['email'] = base64_decode($_REQUEST['email']);
          }
          if (!empty($_REQUEST['password'])) {
            $user['password'] = md5($user['salt'] . $_REQUEST['password']);
          }
          if (isset($_REQUEST['display_name'])) {
            $user['display_name'] = $_REQUEST['display_name'];
          }
          if (isset($_REQUEST['address'])) {
            $end_user['address'] = $_REQUEST['address'];
          }
          if (isset($_REQUEST['phone'])) {
            $end_user['phone'] = $_REQUEST['phone'];
          }
          if (isset($_REQUEST['city_id'])) {
            $end_user['city_id'] = $_REQUEST['city_id'];
          }
          if (isset($_REQUEST['state_id'])) {
            $end_user['state_id'] = $_REQUEST['state_id'];
          }
          if (isset($_REQUEST['country_id'])) {
            $end_user['country_id'] = $_REQUEST['country_id'];
          }
          $errors = array_merge($this->end_user_model->validate($end_user), $this->user_model->validate($user));
          if (empty($errors)) {
            $this->end_user_model->save($end_user);
            echo json_encode(array(
                'msg' => $this->lang->line('message.end_user.update.profile.success'),
                'reason' => '',
                'status' => 1));
          } else {
            echo json_encode(array(
                'msg' => $this->lang->line('message.end_user.update.profile.fail'),
                'reason' => $errors,
                'status' => 0, 'errors' => $errors));
          }
          exit;
        }
      }
    }
    echo json_encode(array(
        'msg' => $this->lang->line('error.authentication.require'),
        'status' => 0,
        'reason' => $this->lang->line('message.require.login.as.end_user')
    ));
    exit;
  }

  protected function _get_promotion_media($promotion_id) {
    if (!empty($promotion_id)) {
      $medias = $this->promotion_media_model->get_all(array('promotion_id' => $promotion_id));
      foreach ($medias as $i => $media) {
        $medias[$i]['path'] = site_url('service/api/get_img_from_path?path=promotion/' . $promotion_id . '/' . $media['path']);
      }
      return $medias;
    }
    return array();
  }

  protected function _get_promotion_download($promotion_id) {
    if (!empty($promotion_id)) {
      return $this->promotion_download_model->count(array('promotion_id' => $promotion_id));
    }
    return 0;
  }

  public function list_promotion() {
    $max = $this->setting_model->item('max_record');
    $offset = empty($_REQUEST['offset']) ? 0 : ($_REQUEST['offset'] + 0);
    $promotions = $this->promotion_model->get_all(array('status' => PROMOTION_PUBLISH,
        'start_date <= ' => time(), 'end_date >= ' => time(), 'remain > ' => 0), null, null, null, null, null, null, null, null, null, null, null, array('end_date' => 'asc'), $max, $offset);
    foreach ($promotions as $i => $promotion) {
      $promotions[$i]['pictures'] = $this->_get_promotion_media($promotion['id']);
      $promotions[$i]['num_got'] = $this->_get_promotion_download($promotion['id']);
      $promotions[$i]['current_time'] = time();
      $promotions[$i]['current_url'] = site_url('promotion/show/' . $promotion['id'] . '/' . str_nice_name($promotion['title']));
      $promotions[$i]['downloaded'] = FALSE;
      $promotions[$i]['favorited'] = FALSE;
      if (userdata('end_user_role') == 'END-USER' || $this->sec(isset($_REQUEST['sec']) ?
                              $_REQUEST['sec'] : '') != null) {
        if (!userdata('end_user_id')) {
          $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
          $end_user_id = $end_user['id'];
        } else
          $end_user_id = userdata('end_user_id');
        $download = $this->db->get_where(DB_TABLE_PROMOTION_DOWNLOAD, array(
                    'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id,
                    'status != ' => PROMOTION_DOWNLOAD_CANCEL,
                    'status != ' => PROMOTION_DOWNLOAD_REJECT), 1, 0)->result();
        if (!empty($download))
          $promotions[$i]['downloaded'] = TRUE;
        $favorite = $this->db->get_where(DB_TABLE_FAVORITE, array(
                    'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id), 1, 0)->result();
        if (!empty($favorite))
          $promotions[$i]['favorited'] = TRUE;
      }
    }
    $temp = json_encode(array(
        'msg' => $this->lang->line('message.promotion.list'),
        'status' => 1, 'reason' => '',
        'promotions' => $promotions));
    echo str_replace('\\/', '/', $temp);
  }

  public function list_promotion_by_category() {
    $temp = array('id' => array(0));
    if (!empty($_REQUEST['category_id'])) {
      $cat_pro = $this->category_promotion_model->get_all(array('cat_id' => $_REQUEST['category_id']));
      if (!empty($cat_pro)) {
        foreach ($cat_pro as $pro) {
          $temp['id'][] = $pro['promotion_id'];
        }
      }
    }
    $max = $this->setting_model->item('max_record');
    $offset = empty($_REQUEST['offset']) ? 0 : ($_REQUEST['offset'] + 0);
    $promotions = $this->promotion_model->get_all(array('status' => PROMOTION_PUBLISH,
        'start_date <= ' => time(), 'end_date >= ' => time(), 'remain > ' => 0), null, $temp, null, null, null, null, null, null, null, null, null, array('end_date' => 'asc'), $max, $offset);
    foreach ($promotions as $i => $promotion) {
      $promotions[$i]['pictures'] = $this->_get_promotion_media($promotion['id']);
      $promotions[$i]['num_got'] = $this->_get_promotion_download($promotion['id']);
      $promotions[$i]['current_time'] = time();
      $promotions[$i]['current_url'] = site_url('promotion/show/' . $promotion['id'] . '/' . str_nice_name($promotion['title']));
      $promotions[$i]['downloaded'] = FALSE;
      $promotions[$i]['favorited'] = FALSE;
      if (userdata('end_user_role') == 'END-USER' || $this->sec(isset($_REQUEST['sec']) ?
                              $_REQUEST['sec'] : '') != null) {
        if (!userdata('end_user_id')) {
          $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
          $end_user_id = $end_user['id'];
        } else
          $end_user_id = userdata('end_user_id');
        $download = $this->db->get_where(DB_TABLE_PROMOTION_DOWNLOAD, array(
                    'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id,
                    'status != ' => PROMOTION_DOWNLOAD_CANCEL,
                    'status != ' => PROMOTION_DOWNLOAD_REJECT), 1, 0)->result();
        if (!empty($download))
          $promotions[$i]['downloaded'] = TRUE;
        $favorite = $this->db->get_where(DB_TABLE_FAVORITE, array(
                    'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id), 1, 0)->result();
        if (!empty($favorite))
          $promotions[$i]['favorited'] = TRUE;
      }
    }
    $temp = json_encode(array(
        'msg' => $this->lang->line('message.promotion.list'),
        'status' => 1,
        'promotions' => $promotions));
    echo str_replace('\\/', '/', $temp);
  }

  public function list_favorite_promotion() {
    if (userdata('end_user_role') == 'END-USER' || $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '') != null) {
      if (!userdata('end_user_id')) {
        $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
        $end_user_id = $end_user['id'];
      } else {
        $end_user_id = userdata('end_user_id');
      }
      $max = $this->setting_model->item('max_record');
      $offset = empty($_REQUEST['offset']) ? 0 : ($_REQUEST['offset'] + 0);
      $promotions = $this->promotion_lib->list_favorite_promotion($end_user_id, $max, $offset);
      foreach ($promotions as $i => $promotion) {
        $promotions[$i]['pictures'] = $this->_get_promotion_media($promotion['id']);
        $promotions[$i]['num_got'] = $this->_get_promotion_download($promotion['id']);
        $promotions[$i]['current_time'] = time();
        $promotions[$i]['current_url'] = site_url('promotion/show/' . $promotion['id'] . '/' . str_nice_name($promotion['title']));
        $promotions[$i]['downloaded'] = FALSE;
        $promotions[$i]['favorited'] = TRUE;
        $download = $this->db->get_where(DB_TABLE_PROMOTION_DOWNLOAD, array(
                    'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id,
                    'status != ' => PROMOTION_DOWNLOAD_CANCEL,
                    'status != ' => PROMOTION_DOWNLOAD_REJECT), 1, 0)->result();
        if (!empty($download))
          $promotions[$i]['downloaded'] = TRUE;
      }
      $temp = json_encode(array(
          'msg' => $this->lang->line('message.list.favorite.promotion'),
          'status' => 1,
          'promotions' => $promotions
              ));
      echo str_replace('\\/', '/', $temp);
    } else {
      echo json_encode(array(
          'msg' => $this->lang->line('error.authentication.require'),
          'status' => 0,
          'reason' => $this->lang->line('message.require.login.as.end_user')
      ));
    }
  }

  public function list_suggest_promotion() {
    
  }

  public function list_near_promotion() {
    if (!empty($_REQUEST['address']) || (!empty($_REQUEST['lat']) && !empty($_REQUEST['lng']))) {
      $this->load->library('promotion_lib');
      if (!empty($_REQUEST['address'])) {
        $promotions = $this->promotion_lib->list_promotion_near_address($_REQUEST['address']);
      } else if (!empty($_REQUEST['lat']) && !empty($_REQUEST['lng'])) {
        $promotions = $this->promotion_lib->list_promotion_near_point($_REQUEST['lat'], $_REQUEST['lng']);
      }
      foreach ($promotions as $i => $promotion) {
        $promotions[$i]['pictures'] = $this->_get_promotion_media($promotion['id']);
        $promotions[$i]['num_got'] = $this->_get_promotion_download($promotion['id']);
        $promotions[$i]['current_time'] = time();
        $promotions[$i]['current_url'] = site_url('promotion/show/' . $promotion['id'] . '/' . str_nice_name($promotion['title']));
        $promotions[$i]['downloaded'] = FALSE;
        $promotions[$i]['favorited'] = FALSE;
        if (userdata('end_user_role') == 'END-USER' || $this->sec(isset($_REQUEST['sec']) ?
                                $_REQUEST['sec'] : '') != null) {
          if (!userdata('end_user_id')) {
            $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
            $end_user_id = $end_user['id'];
          } else
            $end_user_id = userdata('end_user_id');
          $download = $this->db->get_where(DB_TABLE_PROMOTION_DOWNLOAD, array(
                      'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id,
                      'status != ' => PROMOTION_DOWNLOAD_CANCEL,
                      'status != ' => PROMOTION_DOWNLOAD_REJECT), 1, 0)->result();
          if (!empty($download))
            $promotions[$i]['downloaded'] = TRUE;
          $favorite = $this->db->get_where(DB_TABLE_FAVORITE, array(
                      'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id), 1, 0)->result();
          if (!empty($favorite))
            $promotions[$i]['favorited'] = TRUE;
        }
      }
      $temp = json_encode(array(
          'msg' => $this->lang->line('message.promotion.list'), 'status' => 1, 'promotions' => $promotions));
      echo str_replace('\\/', '/', $temp);
    } else {
      echo json_encode(array(
          'msg' => $this->lang->line('error.missing.params'),
          'status' => 0,
          'reason' => $this->lang->line('message.require.params.address')
      ));
    }
  }

  public function search_promotion() {
    /**
     * search for category
     */
    /**
     * by num view
     */
    /**
     * keyword
     */
    if (isset($_REQUEST['keyword'])) {
      $keyword = $_REQUEST['keyword'];
      $where = "(title like '%$keyword%' or description like '%$keyword%') and status = " . PROMOTION_PUBLISH;
      $max = $this->setting_model->item('max_record');
      $offset = empty($_REQUEST['offset']) ? 0 : ($_REQUEST['offset'] + 0);
      $this->db->order_by('end_date', 'asc');
      $promotions = $this->db->get_where(DB_TABLE_PROMOTION, $where, $max, $offset)->result_array();
      foreach ($promotions as $i => $promotion) {
        $promotions[$i]['pictures'] = $this->_get_promotion_media($promotion['id']);
        $promotions[$i]['num_got'] = $this->_get_promotion_download($promotion['id']);
        $promotions[$i]['current_time'] = time();
        $promotions[$i]['current_url'] = site_url('promotion/show/' . $promotion['id'] . '/' . str_nice_name($promotion['title']));
        $promotions[$i]['downloaded'] = FALSE;
        $promotions[$i]['favorited'] = FALSE;
        if (userdata('end_user_role') == 'END-USER' || $this->sec(isset($_REQUEST['sec']) ?
                                $_REQUEST['sec'] : '') != null) {
          if (!userdata('end_user_id')) {
            $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
            $end_user_id = $end_user['id'];
          } else
            $end_user_id = userdata('end_user_id');
          $download = $this->db->get_where(DB_TABLE_PROMOTION_DOWNLOAD, array(
                      'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id,
                      'status != ' => PROMOTION_DOWNLOAD_CANCEL,
                      'status != ' => PROMOTION_DOWNLOAD_REJECT), 1, 0)->result();
          if (!empty($download))
            $promotions[$i]['downloaded'] = TRUE;
          $favorite = $this->db->get_where(DB_TABLE_FAVORITE, array(
                      'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id), 1, 0)->result();
          if (!empty($favorite))
            $promotions[$i]['favorited'] = TRUE;
        }
      }
    } else {
      $promotions = array();
    }
    $temp = json_encode(array(
        'msg' => $this->lang->line('message.promotion.list'),
        'status' => 1, 'promotions' => $promotions));
    echo str_replace('\\/', '/', $temp);
  }

  public function like_promotion() {
    if (userdata('end_user_role') == 'END-USER' || $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '') != null) {
      if (empty($_REQUEST['id'])) {
        echo json_encode(array(
            'msg' => $this->lang->line('error.missing.params'),
            'status' => 0,
            'reason' => $this->lang->line('message.require.params.id')
        ));
      } else {
        $id = $_REQUEST['id'];
        if (!userdata('end_user_id')) {
          $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
          $end_user_id = $end_user['id'];
        } else {
          $end_user_id = userdata('end_user_id');
        }
        $favorite = $this->db->get_where(DB_TABLE_FAVORITE, array(
                    'promotion_id' => $id, 'end_user_id' => $end_user_id), 1, 0)->result();
        if (!empty($favorite)) {
          echo json_encode(array(
              'msg' => $this->lang->line('error.promotion.like.already'),
              'status' => 0,
              'reason' => $this->lang->line('error.promotion.like.already')));
        } else {
          $this->db->insert(DB_TABLE_FAVORITE, array(
              'promotion_id' => $id, 'end_user_id' => $end_user_id, 'date_create' => time()));
          $id = $this->db->insert_id();
          if (!empty($id)) {
            echo json_encode(array(
                'msg' => $this->lang->line('message.promotion.like.success'), 'status' => 1));
          } else {
            echo json_encode(array(
                'msg' => $this->lang->line('error.promotion.like.fatal.error'),
                'status' => 0,
                'reason' => $this->lang->line('error.promotion.like.fatal.error')));
          }
        }
      }
    } else {
      echo json_encode(array(
          'msg' => $this->lang->line('error.authentication.require'),
          'status' => 0,
          'reason' => $this->lang->line('message.require.login.as.end_user')
      ));
    }
  }

  public function get_promotion() {
    if (empty($_REQUEST['id'])) {
      echo json_encode(array(
          'msg' => $this->lang->line('error.missing.params'),
          'status' => 0,
          'reason' => $this->lang->line('message.require.params.id')));
    } else {
      $id = $_REQUEST['id'];
      $promotion = $this->promotion_model->get($id);
      if (!empty($promotion)) {
        $media = $this->_get_promotion_media($promotion['id'], 1);
        $promotion['provider'] = $this->provider_user_model->get($promotion['provider_user_id']);
        $promotion['picture'] = empty($media) ? array() : $media;
        $promotion['num_got'] = $this->_get_promotion_download($id);
        $promotion['current_url'] = site_url('promotion/show/' . $promotion['id'] . '/' . str_nice_name($promotion['title']));
        $promotion['current_time'] = time();
        $temp = json_encode(array(
            'msg' => $this->lang->line('message.promotion.detail'),
            'status' => 1,
            'promotion' => $promotion));
        echo str_replace('\\/', '/', $temp);
      } else {
        echo json_encode(array(
            'msg' => $this->lang->line('error.promotion.not.found'),
            'status' => 0));
      }
    }
  }

  public function download_promotion() {
    if (userdata('end_user_role') == 'END-USER' || $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '') != null) {
      if (empty($_REQUEST['id'])) {
        echo json_encode(array(
            'msg' => $this->lang->line('error.missing.params'), 'status' => 0,
            'reason' => $this->lang->line('message.require.params.id')
        ));
      } else {
        $id = $_REQUEST['id'];
        if (!userdata('end_user_id')) {
          $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
          $end_user_id = $end_user['id'];
        } else {
          $end_user_id = userdata('end_user_id');
        }
        $promotion = $this->promotion_model->get(array('id' => $id, 'status' => PROMOTION_PUBLISH, 'remain > ' => 0));
        if ($promotion) {
          if ($promotion['start_date'] > time()) {
            echo json_encode(array(
                'msg' => $this->lang->line('error.end_user.promotion.not.start'), 'status' => 0,
                'reason' => $this->lang->line('error.end_user.promotion.not.start')
            ));
          } else if ($promotion['end_date'] < time()) {
            echo json_encode(array(
                'msg' => $this->lang->line('error.end_user.promotion.expire'), 'status' => 0,
                'reason' => $this->lang->line('error.end_user.promotion.expire')
            ));
          } else {
            $num_get = empty($_REQUEST['num_get']) ? 1 : ($_REQUEST['num_get']);
            $download = $this->db->get_where(DB_TABLE_PROMOTION_DOWNLOAD, array(
                        'promotion_id' => $id, 'end_user_id' => $end_user_id,
                        'status != ' => PROMOTION_DOWNLOAD_CANCEL,
                        'status != ' => PROMOTION_DOWNLOAD_REJECT), 1, 0)->result();
            if (!empty($download)) {
              echo json_encode(array(
                  'msg' => $this->lang->line('error.promotion.download.already'), 'status' => 0,
                  'reason' => $this->lang->line('error.promotion.download.already')));
            } else {
              $data = array(
                  'promotion_id' => $id, 'end_user_id' => $end_user_id,
                  'code' => strtoupper(substr(md5(time() . uniqid() . time()), 0, 11) . $end_user_id),
                  'num_get' => $num_get, 'status' => PROMOTION_DOWNLOAD_NEW, 'date_create' => time());
              /* call service process download promotion */
              $this->load->library('promotion_lib');
              $send = $this->promotion_lib->download($data);
              ////////////////////////////////////////////
              if ($send) {
                $this->db->insert(DB_TABLE_PROMOTION_DOWNLOAD, $data);
                $download_id = $this->db->insert_id();
                if (!empty($download_id)) {
                  $this->db->where(array('id' => $id));
                  $this->db->update(DB_TABLE_PROMOTION, array('remain' => $promotion['remain'] - $num_get));
                  echo json_encode(array(
                      'msg' => $this->lang->line('message.promotion.download.success'),
                      'status' => 1, 'code' => $data['code']));
                } else {
                  echo json_encode(array(
                      'msg' => $this->lang->line('error.promotion.download.fatal.error'), 'status' => 0,
                      'reason' => $this->lang->line('error.promotion.download.fatal.error')));
                }
              } else {
                echo json_encode(array(
                    'msg' => $this->lang->line('error.promotion.download.fatal.error'), 'status' => 0,
                    'reason' => $this->lang->line('error.promotion.download.fatal.error')));
              }
            }
          }
        } else {
          echo json_encode(array(
              'msg' => $this->lang->line('error.end_user.promotion.not.found'), 'status' => 0,
              'reason' => $this->lang->line('error.end_user.promotion.not.found')));
        }
      }
    } else {
      echo json_encode(array(
          'msg' => $this->lang->line('error.authentication.require'),
          'status' => 0,
          'reason' => $this->lang->line('message.require.login.as.end_user')
      ));
    }
  }

  public function list_downloaded_promotion() {
    if (userdata('end_user_role') == 'END-USER' || $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '') != null) {
      if (!userdata('end_user_id')) {
        $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
        $end_user_id = $end_user['id'];
      } else {
        $end_user_id = userdata('end_user_id');
      }
      $temp = array('id' => array(0));
      $downloaded_promotion = $this->promotion_download_model->get_all(array(
          'end_user_id' => $end_user_id, 'status !=  ' => PROMOTION_DOWNLOAD_CANCEL,
          'status != ' => PROMOTION_DOWNLOAD_REJECT));
      if (!empty($downloaded_promotion)) {
        foreach ($downloaded_promotion as $pro) {
          $temp['id'][] = $pro['promotion_id'];
        }
      }
      $max = $this->setting_model->item('max_record');
      $offset = empty($_REQUEST['offset']) ? 0 : ($_REQUEST['offset'] + 0);
      $promotions = $this->promotion_model->get_all(null, null, $temp, null, null, null, null, null, null, null, null, null, array('end_date' => 'asc'), $max, $offset);
      foreach ($promotions as $i => $promotion) {
        $promotions[$i]['pictures'] = $this->_get_promotion_media($promotion['id']);
        $promotions[$i]['num_got'] = $this->_get_promotion_download($promotion['id']);
        $promotions[$i]['current_time'] = time();
        $promotions[$i]['current_url'] = site_url('promotion/show/' . $promotion['id'] . '/' . str_nice_name($promotion['title']));
        $promotions[$i]['downloaded'] = TRUE;
        $promotions[$i]['favorited'] = FALSE;
        $favorite = $this->db->get_where(DB_TABLE_FAVORITE, array(
                    'promotion_id' => $promotion['id'], 'end_user_id' => $end_user_id), 1, 0)->result();
        if (!empty($favorite))
          $promotions[$i]['favorited'] = TRUE;
      }
      $temp = json_encode(array(
          'msg' => $this->lang->line('message.promotion.list'),
          'status' => 1,
          'promotions' => $promotions));
      echo str_replace('\\/', '/', $temp);
    } else {
      echo json_encode(array(
          'msg' => $this->lang->line('error.authentication.require'),
          'status' => 0,
          'reason' => $this->lang->line('message.require.login.as.end_user')
      ));
    }
  }

  public function list_notification() {
    
  }

  public function list_comment() {
    if (empty($_REQUEST['id'])) {
      echo json_encode(array(
          'msg' => $this->lang->line('error.missing.params'),
          'status' => 0,
          'reason' => $this->lang->line('message.require.params.id')
      ));
    } else {
      $id = $_REQUEST['id'];
      $max = $this->setting_model->item('max_record');
      $offset = empty($_REQUEST['offset']) ? 0 : ($_REQUEST['offset'] + 0);
      $this->db->order_by('date_post', 'desc');
      $comments = $this->db->get_where(DB_TABLE_DISCUSSION, array('promotion_id' => $id), $max, $offset)->result_array();
      foreach ($comments as $i => $comment) {
        $comments[$i]['end_user'] = $this->end_user_model->get($comment['end_user_id']);
        unset($comments[$i]['end_user_id']);
      }
      echo json_encode(array(
          'msg' => $this->lang->line('message.comment.list'),
          'status' => 1,
          'comments' => $comments));
    }
  }

  public function get_comment() {
    if (empty($_REQUEST['id'])) {
      echo json_encode(array(
          'msg' => $this->lang->line('error.missing.params'),
          'status' => 0,
          'reason' => $this->lang->line('message.require.params.id')
      ));
    } else {
      $id = $_REQUEST['id'];
      $comment = $this->db->get_where(DB_TABLE_DISCUSSION, array('id' => $id), 1, 0)->result_array();
      echo json_encode(array(
          'msg' => $this->lang->line('error.comment.detail'),
          'status' => 1,
          'comment' => $comment));
    }
  }

  public function post_comment() {
    if (userdata('end_user_role') != 'END-USER' && $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '') == null) {
      echo json_encode(array(
          'msg' => $this->lang->line('error.authentication.require'),
          'status' => 0,
          'reason' => $this->lang->line('message.require.login.as.end_user')
      ));
    } else {
      if (empty($_REQUEST['promotion_id'])) {
        echo json_encode(array(
            'msg' => $this->lang->line('error.missing.params'),
            'status' => 0,
            'reason' => $this->lang->line('message.require.params.promotion_id')
        ));
      } else {
        if (!userdata('end_user_id')) {
          $end_user = $this->sec(isset($_REQUEST['sec']) ? $_REQUEST['sec'] : '');
          $end_user_id = $end_user['id'];
        } else {
          $end_user = $this->end_user_model->get(userdata('end_user_id'));
          $end_user_id = userdata('end_user_id');
        }
        $promotion_id = $_REQUEST['promotion_id'];
        $title = isset($_REQUEST['title']) ? $_REQUEST['title'] : $end_user['email'];
        $content = isset($_REQUEST['content']) ? $_REQUEST['content'] : '';
        if (!empty($title) && !empty($content)) {
          $this->db->insert(DB_TABLE_DISCUSSION, array('promotion_id' => $promotion_id,
              'title' => $title, 'content' => $content, 'date_post' => time(), 'end_user_id' => $end_user_id));
//          $id = $this->db->insert_id();
          echo json_encode(array('msg' => $this->lang->line('message.comment.success'), 'status' => 1
          ));
        } else {
          echo json_encode(array(
              'msg' => $this->lang->line('error.params.not.blank'), 'status' => 0,
              'reason' => $this->lang->line('error.params.not.blank')
          ));
        }
      }
    }
  }

  public function get_img_from_path() {
    $path = empty($_REQUEST['path']) ? '' : $_REQUEST['path'];
    $this->base_lib->get_img_from_path($this->setting_model->item('upload_path') . $path);
  }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */